<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\Problem;
use App\Models\Product;
use Illuminate\Http\Request;

class ProblemController extends BaseController
{
    public $model = Problem::class;

    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $users = Problem::when($title, function ($q) use($title){
            $q->where('title', 'like', '%' . $title . '%');
        })->orderBy('sort', 'desc')->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($users);
    }

    /**
     * 详情
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function info(Request $request) {
        $this->validate($request, [
            'id' => 'required|exists:problems'
        ]);
        $id = \request("id");
        $info = Problem::find($id);
        return $this->success($info);
    }

    /**
     * 保存|修改
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function store(Request $request) {
        $this->validate($request, [
            'sort' => 'filled|integer',
            'title' => 'required',
            'answer' => 'required',
        ]);
        $input = $request->input();
        $id = \request("id");
        if ($id) {
            $problem = Problem::where('id', $id)->first();
            if (!$problem)
                return $this->failed('ID对应数据不存在');
            $problem->update($input);
        } else {
            $info = Problem::create($input);
            $id = $info->id;
        }
        return $this->success($id);
    }




}

